3SUM
Table of Contents
Overview1
In computational complexity theory, 3SUM is the following computational problem conjectured to require roughly quadratic time:
Given a set S of n integers, are there elements a, b, c in S such that a + b + c = 0?
It is possible to solve the algorithm in O(n2) time using simple algorithms, and matching lower bounds are known for some specialized models of computation. Slightly faster randomized algorithms are known that exploit computational-model parallelism on a RAM and in the external-memory and cache-oblivious models (Baran, Demaine & Pǎtraşcu 2008). When the integers are in the range [−u … u], 3SUM can be solved in time O(n + u lg u) by representing S as a bit vector, determining S + S by performing a discrete convolution using FFT, and then comparing to -S.
Quadratic algorithm
sort(S); for i=0 to n-3 do a = S[i]; k = i+1; l = n-1; while (k<l) do b = S[k]; c = S[l]; if (a+b+c == 0) then output a, b, c; exit; else if (a+b+c > 0) then l = l - 1; else k = k + 1; end end end